//
//  TKIMTextView.m
//  TKIM_首创
//
//  Created by thinkive on 15/12/18.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMTextView.h"

@implementation TKIMTextView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //注册通知 当这个textView内容改变时，自己调用textDidChange这个方法。
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
        
    }
    return self;
}

#pragma mark - setter方法
-(void)setPlaceHolder:(NSString *)placeHolder
{
    _placeHolder = [placeHolder copy];
    [self setNeedsDisplay];
}
-(void)setPlaceHolderColor:(UIColor *)placeHolderColor
{
    _placeHolderColor = placeHolderColor;
    [self setNeedsDisplay];
}
//当通过代码修改text的值时，不会发送文字改变的通知，故要重写该方法，手动重绘。
-(void)setText:(NSString *)text
{
    [super setText:text];
    [self setNeedsDisplay];
}

-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    [self setNeedsDisplay];
}

-(void)textDidChange
{
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    //textView中有内容直接返回，否则画默认文字
    if (self.hasText) return;
    NSMutableDictionary * attrsDic = [NSMutableDictionary dictionary];
    attrsDic[NSFontAttributeName] = self.font;
    attrsDic[NSForegroundColorAttributeName] = self.placeHolderColor?self.placeHolderColor:[UIColor grayColor];
    CGFloat x = 5.0;
    CGFloat y = 8.0;
    CGFloat width = rect.size.width - 2 * x;
    CGFloat height = rect.size.height - 2 * y;
    [self.placeHolder drawInRect:CGRectMake(x, y, width, height) withAttributes:attrsDic];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
